package models

import (
	"3rd/mongo"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
		goerrors "github.com/go-errors/errors"
)

type Product struct {
	Quality     int    `bson:"quality,omitempty" json:"quality,omitempty"`
	Pic         string `bson:"pic,omitempty" json:"pic,omitempty"`
	Name        string `bson:"name,omitempty" json:"name,omitempty"`
	Description string `bson:"description,omitempty" json:"description,omitempty"`
}

type Provider struct {
	ProviderID string    `bson:"_id" json:"providerID,omitempty"`
	Company    string    `bson:"company,omitempty" json:"company,omitempty"`
	Alias      string    `bson:"alias,omitempty" json:"alias,omitempty"`
	Telephone  []string  `bson:"telephone,omitempty" json:"telephone,omitempty"`
	Website    string    `bson:"website,omitempty" json:"website,omitempty"`
	Address    string    `bson:"address,omitempty" json:"address,omitempty"`
	Products   []Product `bson:"products,omitempty" json:"products,omitempty"`
	Created    int64     `bson:"created,omitempty" json:"created,omitempty"`
}

func AddProvider(provider *Provider) error {
	return mongo.DO(db_provider, col_provider, func(c *mgo.Collection) (err error) {
		if err := c.Insert(provider); err != nil {
			return goerrors.New(err)
		}
		return nil
	})
}

func GetProvidersBriefly(providers *[]Provider) error {
	return mongo.DO(db_provider, col_provider, func(c *mgo.Collection) (err error) {
		if err := c.Find(nil).Select(bson.M{"company": 1, "_id": 1}).All(providers); err != nil {
			return goerrors.New(err)
		}
		return nil
	})
}

func RmProvider(providerID string) error {
	return mongo.DO(db_provider, col_provider, func(c *mgo.Collection) (err error) {
		if err := c.RemoveId(providerID); err != nil {
			return goerrors.New(err)
		}
		return nil
	})
}

func UpdateProvider(provider *Provider) error {
	return mongo.DO(db_provider, col_provider, func(c *mgo.Collection) (err error) {
		if err := c.UpdateId(provider.ProviderID, provider); err != nil {
			return goerrors.New(err)
		}
		return nil
	})
}

func GetProvider(id string, provider *Provider) error {
	return mongo.DO(db_provider, col_provider, func(c *mgo.Collection) (err error) {
		if err := c.FindId(id).One(provider); err != nil {
			return goerrors.New(err)
		}
		return nil
	})
}

func GetProviders(ids []string, providers *[]Provider) error {
	return mongo.DO(db_provider, col_provider, func(c *mgo.Collection) (err error) {
		query := bson.M{"_id": bson.M{"$in": ids}}
		if err := c.Find(query).All(providers); err != nil {
			return goerrors.New(err)
		}
		return nil
	})
}
